package org.laobai.shop.goods.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.dubbo.config.annotation.DubboService;
import org.laobai.shop.goods.entity.Sku;
import org.laobai.shop.goods.entity.SpecOption;
import org.laobai.shop.goods.mapper.SkuMapper;
import org.laobai.shop.goods.service.SkuService;
import org.laobai.shop.goods.vo.SkuVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;

@DubboService
public class SkuServiceImpl implements SkuService{
	@Autowired
	private  SkuMapper skuMapper;
	
	@Override
	public boolean saveSku(Sku sku) {
		// 保存SKU
		sku.setCreateTime(new Date());
		sku.setUpdateTime(sku.getCreateTime());
		skuMapper.saveSku(sku);
		Integer skuId = sku.getId();
		List<SpecOption> specs = sku.getSpecs();
		if(!CollectionUtils.isEmpty(specs)){
			Map<String, Object> map = new HashMap<String, Object>();
			specs.forEach(item->{
				map.put("skuId", skuId);
				map.put("spec", item);
				skuMapper.saveSkuSpec(map);
				map.clear();
			});
		}
		return true;
	}

	@Override
	public List<Sku> getBySpuId(Integer spuId) {
		return skuMapper.getBySpuId(spuId);
	}

	@Override
	public Sku getSku(List<SkuVO> vos) {
		if(CollectionUtils.isEmpty(vos)){
			return new Sku();
		}
		List<Set<Sku>> result = new ArrayList<>();
		
		Set<Sku> skus = null;
		for (SkuVO vo :vos){
			skus = skuMapper.getSkuBySpec(vo.getSpecId(),vo.getOptionId());
			result.add(skus);
		}
		Set<Sku> set = result.get(0);
		for(int i = 1;i<result.size();i++){
			// 交集
			set.retainAll(result.get(i));
		}
		return new ArrayList<>(set).get(0);
	}

}
